# We define the test module.  The test module depends on a number of Javascript
# files, which must all be downloaded before the module can execute.
define [
	'jquery'
	'template'
	'lib/jquery.couch.js'
	'helper'
], ($, undef, undef, H) ->


	# Upon loading the dependencies, we will define a jQuery plugin. By
	# convention for this project, we will prepend 'mb_' to the plugin name to
	# avoid conflicts.
	$.fn.mb_test = (S) ->
		# If plugin has not been set up
		unless @mb_plugin()
			@mb_plugin 'test'
			# Show title in the container in which this plugin will be applied to.
			@prepend $('<h3>').text 'Test Page'
			return @

		# Run the test sequence each time this plugin is applied.
		$results = $('#results', @)
		# Test that the pubsub mechanism is available by having the plugin
		# publish a text message to itself.
		$.publish 'mb.test', 'no subscription, now subscribing'
		$.subscribe 'mb.test', (e, x) => $results.append $('<li>').text x
		$.publish 'mb.test', 'subscribed, now unsubscribing'
		$.unsubscribe 'mb.test'
		$.publish 'mb.test', 'unsubscribed, now re-subscribing'
		$.subscribe 'mb.test', (e, x) => $results.append $('<li>').text x
		$.publish 'mb.test', 'subscription restored'

		# Test that Sammy context is available by having it return the ID of
		# the app container.
		$.publish 'mb.test', "application is bound to ##{S.$element().prop 'id'}"

		# Test that jquery.couch is available by having it connect to the
		# project database and showing its name.
		db = H.db()
		$.publish 'mb.test', "connected to database #{db.name}"

		# Test the use of jQuery template() method by defining a template in
		# the DOM and pulling it out for use here.
		tpl = $('#tpl_place').template()
		$.publish 'mb.test', "rendered template #{tpl}"

		# Test the use of S.content() by using sample data to generate sample
		# content.
		content = S.content $('#tpl_place', @),
			city: 'oslo'
			country: 'norway'
		# New content can replace old content in two ways...
		$('#content_place', @).replaceWith content
		$(content).replaceAll $('#content_place', @)

		# Test that template is not cached by replacing template with its
		# own content and then trying to use it again to render new
		# content.
		content = S.content $('#tpl_place', @),
			city: 'osh'
			country: 'kyrgyzstan'
		$(content).replaceAll $('#tpl_place', @)
		content = S.content $('#tpl_place', @),
			city: 'aqaba'
			country: 'jordon'
		$(content).appendTo $results
		# content is null because $.template() called by S.content() does
		# not find template anymore.

		# Test that click handler will allow the click event to propagate to
		# site.js where it can trigger a page change.
		@on 'click', 'input[name="test"]', ->
			$.publish 'mb.test', 'changing page'

		S.app.bind 'location-changed', (e) -> false


		# Begin a sequence to test authentication 
		userTestName = 'testName'
		userTestPass = 'test1234'
		userDoc =
			_id: "org.couchdb.user:#{userTestName}"
			name: userTestName
		error = (status) -> console.log status

		# Create a test user doc
		$.couch.signup userDoc, userTestPass,
			error: error
			success: (resp) ->
				$.publish 'mb.test', "created test user doc #{resp.id}"
				userDoc._rev = resp.rev

				# Log in as the test user
				$.couch.login
					error: error
					name: userTestName
					password: userTestPass
					success: (resp) ->
						$.publish 'mb.test', "created authenticated session with #{resp.name}"

						# Confrim that we are in an authenticated session
						$.couch.session
							error: error
							success: (resp) ->
								$.publish 'mb.test', "authenticated session is #{resp.info.authenticated}"

								# While in an authenticated session, try to read system user db
								$.couch.db('_users').openDoc "org.couchdb.user:#{userTestName}",
									error: (status) ->
										$.publish 'mb.test', "was not able to open up org.couchdb.user:#{userTestName}; unexpected"
									success: (resp) ->
										$.publish 'mb.test', "was able to open up org.couchdb.user:#{userTestName}; expected"

								# While in an authenticated session, try to get all test suite reports
								$.couch.db('test_suite_reports').allDocs
									error: (status) ->
										reason = @error.arguments[2]
										$.publish 'mb.test', "was not able to get all test suite reports, '#{reason}'"
									success: (resp) ->
										$.publish 'mb.test', "was able to get #{resp.total_rows} test suite reports; unexpected"

								# Log out of authenticated session
								$.couch.logout
									error: error
									success: (resp) ->
										$.publish 'mb.test', "removed authenticated session"

										# Remove the test user doc
										$.couch.db('_users').removeDoc userDoc,
											error: error
											success: (resp) -> $.publish 'mb.test', "removed test user doc #{resp.id}"

		return @
	return
